<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="生产流程模板">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" :allowClear="true"
                            @search="handleSearch" v-model="pageData.dropDownData" :filter-option="false" allow-search
                            @focus="focusSel">
                            <a-option v-for="item in pageData.clothList" :value="item['productionCode']">{{
                            item['productionCode'] }}</a-option>
                        </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.dropDownData"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            style="float: right"
            :items="['查询', '新增', '删除']"
            @add="addHandler"
            @import="importHandler"
            @del="deleteHandler"
            @select="selectHandler"
            @export="exports"
            @excel="downloadHandler"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <!-- 主表 -->
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 100%"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
      ></AgGridVuesCopys>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :page-size="pagination.pageSize"
      :current="pagination.page"
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
    />
    <!-- 主表抽屉 -->
    <a-drawer
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      cancel-text="关闭"
      ok-text="保存"
      :ok-loading="pageData.pageLoading"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="80px"
            label="流程编号"
            field="productionCode"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '流程编号必填' }]"
          >
            <a-input class="bacClass" placeholder=" " v-model="dataForm.productionCode" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="流程名称"
            field="flowName"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '流程名称必填' }]"
          >
            <a-input class="bacClass" placeholder=" " v-model="dataForm.flowName" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="流程类别"
            field="flowPathType"
            :validate-trigger="['change', 'blur']"
            :rules="[{ required: true, message: '流程类别必填' }]"
          >
            <!-- <a-input class="bacClass" placeholder=" " v-model="dataForm.flowPathType" /> -->
            <a-select
              popup-container="html"
              class="bacClass"
              :style="{ width: '400px' }"
              :loading="loading"
              @search="handleSearchw1"
              v-model="dataForm.flowPathType"
              :filter-option="false"
              allow-search
              allow-clear
              @focus="focusSelw1"
            >
              <a-option v-for="item in pageData.nameListw1" :value="item">{{ item }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注">
            <a-textarea
              class="bacClass"
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <!-- 子表抽屉 -->
    <a-drawer
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd1"
      unmountOnClose
      @ok="sideOk1"
      @cancel="pageData.showAdd1 = false"
      cancel-text="关闭"
      ok-text="保存"
      :ok-loading="pageData.pageLoading2"
    >
      <template #title>
        {{ pageData.sideTitle1 }}
      </template>
      <div>
        <a-form ref="formRef1" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="80px"
            label="工段"
            field="sectionId"
            :rules="[{ required: true, message: '工段必选' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              @search="sectionSearch(dataForm.sectionId)"
              @focus="sectionSearch('')"
              @change="sectionChange"
              :filter-option="false"
              allow-search
              v-model="dataForm.sectionId"
              allow-clear
            >
              <a-option v-for="item in pageData.sectionList" :value="item.id" :key="item.id">
                {{ item.sectionName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="工序"
            :validate-trigger="['change', 'blur']"
            field="processId"
            :rules="[{ required: true, message: '工序必填' }]"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              :loading="loading1"
              @search="processSearch(dataForm.processId)"
              @focus="processSearch('')"
              v-model="dataForm.processId"
              :filter-option="false"
              allow-search
              allow-clear
            >
              <a-option v-for="item in pageData.nameList" :value="item.id" :key="item.processName">
                {{ item.processName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="设备类型">
            <a-select
              popup-container="html"
              class="bacClass"
              allow-search
              allowClear
              :loading="loading1"
              @search="handleSearchs1"
              :filter-option="false"
              v-model="dataForm.typeName"
              @focus="focusSel2"
            >
              <a-option v-for="item in pageData.typeList" :value="item" :key="item">{{
                item
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="工具">
            <a-input class="bacClass" placeholder="请输入工具" v-model="dataForm.functionalTool" />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <!-- 子表 -->
    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 999 }"
      :mask-closable="false"
      :width="400"
      popup-container=".main-base-style"
      height="100%"
      :visible="pageData2.showAdd"
      placement="bottom"
      @ok="sideNo1"
      @cancel="closeNo"
      :ok-loading="pageData.pageLoading1"
    >
      <template #title> 生产流程 </template>
      <template #footer><a-button @click="closeNo">关闭</a-button></template>
      <div class="my-tool-bar">
        <Toolbar
          :items="['新增', '删除']"
          @add="addHandler1"
          @import="importHandler"
          @del="deleteHandler1"
          @select="selectHandler"
          @export="exports"
          @excel="downloadHandler"
        >
        </Toolbar>
      </div>
      <!-- <a-tabs   :justify="true">
                <a-tab-pane> -->
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReady1"
        style="height: 100%"
        :defaultColDef="defaultColDef1"
        class="ag-theme-alpine"
        :rowData="pageData.dataList"
        :columnDefs="tableColumns1"
        :localeText="localeText1"
        :rowDragManaged="true"
        :animateRows="true"
        @rowDragEnd="onRowDragEnd"
      >
      </AgGridVuesCopys>
      <!-- </a-tab-pane>
            </a-tabs> -->
      <!-- <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize"
           @page-size-change="change2" style="justify-content: center" /> -->
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import { pagingList } from '@/api/paging'
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import { localeText } from '@/api/aggridZw'
import { ref, reactive, onMounted, onActivated, onUnmounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Form, Message, Modal, Pagination } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import emitter from '@/hooks/useEventBus'
import validate from '@/hooks/useValidate'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'

import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { data } from 'autoprefixer'
interface ClothSet {
  id: any
  serialNumber: number | undefined
  productionCode: string | undefined
  deleteState: any
  remark: string | undefined
  createName: string | undefined
  createTime: string | undefined
  updateName: string | undefined
  updateTime: string | undefined
  requireClassify: any
  parameters: any
  defaultx: any
  parameterValues: any
  productProcessID: any
  flowName: any
  flowPathType: any
  functionalTool: any
  typeName: any
  deviceType: any
  sectionName: any
  sectionId: any
  processName: any
  processId: any
}

export default {
  name: 'ProductionProcess',
  setup() {
    const headerShow = ref<boolean>(true)
    //主表分页查询
    const scrollbar = ref(true)

    function doRefresh() {
      pageData.pageLoading = true

      post({
        url: 'pdm/ProductProcess/getPage',
        data: {
          page: pagination.page,
          size: pagination.pageSize,
          deleteState: 0,
          productionCode: pageData.dropDownData,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.list)
            gridOption.value.setRowData(data.list)
            total.value = data.total
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const table1 = useTable()
    const rowKey = useRowKey('id')
    //检验表单是否含有中文的方法
    const hasChiese = validate.includeChinese
    const tableColumns = useTableColumn([
      {
        title: '序号',
        key: 'serialNumber',
        dataIndex: 'serialNumber',
        width: 150,
      },
      {
        title: '生产流程编号',
        key: 'productionCode',
        dataIndex: 'productionCode',
        width: 150,
      },
      {
        title: '生产流程',
        key: 'flows',
        dataIndex: 'flows',
        width: 450,
        // slotName: 'act1',
      },
      {
        title: '生产流程名称',
        key: 'flowName',
        dataIndex: 'flowName',
        width: 150,
      },
      {
        title: '流程类别',
        key: 'flowPathType',
        dataIndex: 'flowPathType',
        width: 150,
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
        width: 150,
      },
      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
        width: 150,
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        width: 150,
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
        width: 150,
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
        width: 150,
      },
      {
        title: '操作',
        key: 'id',
        dataIndex: 'id',
        slotName: 'act',
        width: 150,
        fixed: 'right',
      },
    ])

    const tableColumns1: any = [
      {
        field: '',
        pinned: 'left',
        rowDrag: (params: any) => {
          return !(params.data.serialNumber == null)
        },
        width: 50,
      },
      {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
      },
      {
        headerName: '顺序号',
        field: 'serialNumber',
        width: 150,
      },
      {
        headerName: '工段',
        field: 'sectionName',
        width: 150,
      },
      {
        headerName: '工序',
        field: 'processName',
        width: 150,
      },
      {
        headerName: '设备类型',
        field: 'typeName',
        width: 150,
      },
      {
        headerName: '实用工具',
        field: 'functionalTool',
        width: 150,
      },
      {
        headerName: '创建人',
        field: 'createName',
        width: 150,
      },
      {
        headerName: '创建时间',
        field: 'createTime',
        width: 150,
      },
      {
        headerName: '操作',
        field: 'id',
        width: 150,
        fixed: 'right',
        cellRenderer: {
          template: `<el-button style="color:#165dff;" @click="b" class="gesture" link>修改</el-button>`,
          setup(props: any) {
            const b = () => {
              editHandler2(props.params.data)
            }
            return {
              b,
            }
          },
        },
      },
    ]
    const scroll = {
      x: 2000,
      y: 200,
    }
    const tablediv = ref(null)
    const pageData = reactive<{
      clothList: ClothSet[]
      showAdd: boolean
      showAdd1: boolean
      showAdd2: boolean
      sideTitle: string
      sideTitle1: string
      dropDownData: any
      pageLoading: boolean
      pageLoading1: boolean
      pageLoading2: boolean
      theight: number
      tablediv: any
      rHeight: number | undefined
      nameList: any
      nameListw1: []
      dataList: any
      sectionList: any[]
      typeList: any[]
    }>({
      clothList: [],
      sideTitle1: '新增生产流程',
      showAdd: false,
      showAdd1: false,
      showAdd2: false,
      sideTitle: '新增生产流程模板',
      dropDownData: '',
      pageLoading: false,
      pageLoading1: false,
      pageLoading2: false,
      theight: 0,
      tablediv: null,
      rHeight: 0,
      nameList: '',
      nameListw1: [],
      dataList: [],
      sectionList: [],
      typeList: [],
    })
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({ productionCode: '' })
    }
    //下拉数据
    const options = ref<any>(pageData.clothList)
    const loading = ref(false)
    const handleSearch = (value: any) => {
      if (value) {
        const ob = { productionCode: value }
        loading.value = true
        selCxAll(ob)
        options.value = pageData.clothList
        loading.value = false
      } else {
        options.value = []
      }
    }

    //主表下拉框查询
    function selCxAll(val: any) {
      post({
        url: 'pdm/ProductProcess/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.clothList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    //下拉框得到焦点
    const focusSel2 = () => {
      selCxAll2({ typeName: '' })
    }

    //下拉数据
    const options12 = ref<any>(pageData.typeList)
    const loading2 = ref(false)
    const handleSearchs1 = (value: any) => {
      if (value) {
        const ob = { typeName: value, deleteState: 0 }
        loading2.value = true
        selCxAll2(ob)
        options12.value = pageData.typeList
        loading2.value = false
      } else {
        options12.value = []
      }
    }
    //下拉框查询
    function selCxAll2(val: any) {
      post({
        url: 'aps/dwMachineType/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          console.log(data)
          let dataList: any = []
          data.forEach(function (o: any) {
            dataList.push(o['typeName'])
          })
          pageData.typeList = dataList
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    onMounted(() => {
      // 第一个页面需要在刚进入就调用一次  切换tap时也需要调用
      doRefresh()
      sectionSearch('')
      processSearch('')
      // selCxAll({});
      // 切换tap到本页面执行的方法
      emitter.on('ProductionProcess', () => {
        // selCxAll({});
        doRefresh()
      })
      pageData2.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
      //弹出层的高
      if (pageData2.rHeight !== undefined) {
        pageData2.rHeight = pageData2.rHeight - 50
      }
    })
    let cxbl = ''
    //主表查询按钮事件
    const selectHandler = () => {
      pagination.page = 1
      // cxbl = pageData.dropDownData
      if (pageData.dropDownData !== '') {
        doRefresh()
      } else {
        doRefresh()
      }
    }
    const queryData = reactive({
      clothType: '',

      typeCode: '',
    })
    // 主表添加按钮事件
    const addHandler = () => {
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else {
          dataForm[key] = ''
        }
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增生产流程模板'
    }
    // 子表添加按钮事件
    const addHandler1 = () => {
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else {
          dataForm[key] = ''
        }
      }
      pageData.showAdd1 = true
      pageData.sideTitle1 = '新增生产流程'
    }
    const dataForm = reactive<ClothSet>({
      id: null,
      serialNumber: 0,
      createTime: '',
      productionCode: '',
      remark: '',
      updateTime: '',
      updateName: '',
      createName: '',
      deleteState: 0,
      requireClassify: '',
      parameters: '',
      defaultx: '',
      parameterValues: '',
      productProcessID: '',
      flowName: '',
      flowPathType: '',
      functionalTool: '',
      typeName: '',
      deviceType: '',
      sectionName: '',
      sectionId: null,
      processName: '',
      processId: null,
    })

    // 主表新增，修改保存事件
    const formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          pageData.pageLoading = true
          if (pageData.sideTitle === '新增生产流程模板') {
            post({
              url: 'pdm/ProductProcess/insert',
              data: [dataForm],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields()
                pageData.showAdd = false
                pageData.pageLoading = false
                Message.success({
                  content: '新增成功',
                  duration: 5000,
                })
                doRefresh()
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                })
              }
            })
          } else {
            post({
              url: 'pdm/ProductProcess/update',
              data: [dataForm],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields()
                pageData.showAdd = false
                pageData.pageLoading = false
                Message.success({
                  content: '修改成功',
                  duration: 5000,
                })
                doRefresh()
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                })
              }
            })
          }
        }
      })
    }
    // 子表新增，修改保存按钮事件
    const formRef1 = ref<FormInstance>()
    const sideOk1 = () => {
      formRef1.value?.validate().then((err) => {
        if (!err) {
          pageData.pageLoading2 = true
          dataForm.processName = pageData.nameList.find(
            (o: any) => o.id == dataForm.processId
          ).processName
          if (pageData.sideTitle1 === '新增生产流程') {
            post({
              url: 'pdm/ProductProcessSon/insert',
              data: {
                productProcessID: keyList.shelveId,
                typeName: dataForm.typeName,
                sectionId: dataForm.sectionId,
                sectionName: dataForm.sectionName,
                processId: dataForm.processId,
                processName: dataForm.processName,
                functionalTool: dataForm.functionalTool,
                serialNumber: pageData.dataList.length + 1,
              },
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields()
                pageData.showAdd1 = false
                pageData.pageLoading2 = false
                Message.success({
                  content: '新增成功',
                  duration: 5000,
                })
                doRefresh1()
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                })
              }
            })
          } else {
            post({
              url: 'pdm/ProductProcessSon/update',
              data: dataForm,
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields()
                pageData.showAdd1 = false
                pageData.pageLoading2 = false
                Message.success({
                  content: '修改成功',
                  duration: 5000,
                })
                doRefresh1()
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                })
              }
            })
          }
          pageData.pageLoading2 = false
        }
      })
    }
    // 主表删除按钮事件
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          post({
            url: 'pdm/ProductProcess/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          }).then(({ code, data, message }: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000,
              })

              pagination.page = 1
              doRefresh()
            } else {
              Message.error({
                content: '删除失败',
                duration: 5000,
              })
            }
          })
        },
      })
    }
    // 子表删除按钮事件
    const deleteHandler1 = () => {
      if (gridOption1.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      let datas = pageData.dataList.filter((rowData: any) => {
        return !gridOption1.value
          .getSelectedRows()
          .some((selectedRow: any) => selectedRow.id === rowData.id)
      })
      console.log(datas)
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          post({
            url: 'pdm/ProductProcessSon/delete',
            data: datas,
          }).then(({ code, data, message }: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000,
              })
              pagination.page = 1
              doRefresh1()
            } else {
              Message.error({
                content: '删除失败',
                duration: 5000,
              })
            }
          })
        },
      })
    }
    // 主表修改按钮事件
    const editHandler = (record: any) => {
      for (var key in record) {
        dataForm[key] = record[key]
      }
      pageData.sideTitle = '修改项目'
      pageData.showAdd = true
    }
    // 子表修改按钮事件
    const editHandler2 = (record: any) => {
      console.log(record, 'record')
      for (var key in record) {
        dataForm[key] = record[key]
      }
      pageData.sideTitle1 = '修改流程'
      pageData.showAdd1 = true
    }

    //导出
    const exports = () => {
      if (selectedRowKeys.value.length === 0) {
        Message.error('请先勾选')
        return
      } else {
        //将表头拼接出来
        let head =
          '<th>编号</th><th>名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return selectedRowKeys.value.indexOf(o['id']) !== -1
        })
        let body = ''
        nowRow.forEach(function (o) {
          body += '<tr><td>' + o['merceryCode'] + '</td>'
          body += '<td>' + o['merceryName'] + '</td>'
          body += '<td>' + o['remark'] + '</td>'
          body += '<td>' + o['createName'] + '</td>'
          body += '<td>' + o['createTime'] + '</td>'
          body += '<td>' + o['updateName'] + '</td>'
          body += '<td>' + o['updateTime'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '布类资料', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
           <head><meta charset="UTF-8"></head>
           <body><table border="1"><tr>${head}</tr>${body}</table></body>
       </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
        .get(baseURL + '/product/mercery/uploadMerceryModel', {
          responseType: 'blob',
          headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
          },
        })
        .then((res) => {
          if (res.status === 200) {
            filedownload(res.data, '布类资料.xlsx')
          }
        })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
          .post(baseURL + '/product/mercery/analyseMerceryModel', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((result) => {
            if (result.data['code'] === 200) {
              Message.success('导入成功')
            } else {
              Message.error(result.data.message)
            }
          })
          .finally(() => {
            pageData.pageLoading = false
            doRefresh()
          })
      })
      inputEle.click()
    }
    const pageData2 = reactive<{
      showAdd: boolean
      rHeight: any
    }>({
      showAdd: false,
      rHeight: 0,
    })
    interface keyscwType {
      firm: any
      warehouseId: any
      warehouseName: any
      id: any
      name: any
      shelveName: any
    }
    let keyscw: keyscwType = {
      firm: '',
      warehouseId: '',
      warehouseName: '',
      id: '',
      name: '',
      shelveName: '',
    }
    // 定义从主表获取过来的数据
    let keyList = {
      shelveId: 0,
      shelveName: '',
      sheID: '',
    }
    // const listopen = ref([])
    // 子表查询渲染
    function doRefresh1() {
      pageData.pageLoading = true

      post({
        url: 'pdm/ProductProcess/getListId',
        data: {
          id: keyList.shelveId,
          // classify: keyList.shelveName,
          // deleteState:0,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            pageData.dataList = data.list
            // gridOption1.value.setRowData(data.list)
            total.value = data.total
            gridOption1.value.sizeColumnsToFit()
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
    // 点击按钮获取主表数据
    const editHandler1 = (key: any) => {
      keyList.shelveId = Number(key.id)
      keyList.shelveName = key.productionCode
      // keyList.sheID = dataForm.defaultx
      // opCwdata(keyList)
      // keyscw = key
      pageData2.showAdd = true
      doRefresh1()
    }

    let lengsDs: number = 0
    // 表格准备事件
    const gridOption = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        width: o['width'],
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'
        obj['width'] = 165
        obj['cellRenderer'] = {
          //template: `<a-space><a-tag color="#ff7d00" @click="a" class="gesture">修改</a-tag><a-tag color="#41b349" @click="c" class="gesture">生成流程</a-tag></a-space>`,
          template: `<a-space><el-button style="color:#165dff;"  type="info" link @click="a">修改</el-button>
                     <el-button style="color:#165dff;"  type="info" link @click="c">生成流程</el-button>
                     </a-space>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            const c = () => {
              editHandler1(props.params.data)
            }
            return {
              a,
              c,
            }
          },
        }
      }
      if (o.slotName === 'act1') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['width'] = 300
      }

      return obj
    })
    // 子表表格准备事件
    const gridOption1 = ref()
    const gridReady1 = (params: any) => {
      gridOption1.value = params.api
    }
    const defaultColDef1 = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const total = ref(10)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      pagination.page = val
      doRefresh()
    }
    function change1(val: any) {
      pagination.pageSize = val
      doRefresh()
    }
    function change2(val: any) {
      pagination.pageSize = val
      doRefresh1()
    }
    // 子表保存按钮事件
    const sideNo1 = () => {
      //1 拿到后段需要的传参
      // let list: any = []
      // gridOption1.value.getSelectedRows().forEach(function (o: any) {
      //     list.push(o['productProcessID'])
      //     list.push(o['processName'])
      // })
      // console.log(gridOption1.value.getSelectedRows(), '2121212112121212');

      if (gridOption1.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }
      pageData.pageLoading1 = true
      post({
        url: 'pdm/ProductProcess/updateFlows',
        data: gridOption1.value.getSelectedRows(),
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            pageData2.showAdd = false
            pageData.pageLoading1 = false
            doRefresh()
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading1 = false
        })
    }
    const checkeded = ref<boolean>()
    // 子表关闭
    const closeNo = () => {
      pageData2.showAdd = false
      doRefresh()
    }
    const localeText1: any = ref(localeText)
    const huiche = () => {
      doRefresh()
    }
    const pagingList1: any = ref(pagingList)

    //下拉框得到焦点
    const focusSelw1 = () => {
      selCxAllw1({ flowPathType: '' })
    }

    //下拉数据
    const optionsw1 = ref<any>(pageData.nameListw1)
    const loadingw1 = ref(false)
    const handleSearchw1 = (value: any) => {
      if (value) {
        const ob = { flowPathType: value, deleteState: 0 }
        loadingw1.value = true
        selCxAllw1(ob)
        optionsw1.value = pageData.nameListw1
        loadingw1.value = false
      } else {
        optionsw1.value = []
      }
    }
    //下拉框查询
    function selCxAllw1(val: any) {
      post({
        url: 'pdm/FlowpathType/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          console.log(data)
          let dataList: any = []
          data.forEach(function (o: any) {
            dataList.push(o['flowPathType'])
          })
          pageData.nameListw1 = dataList
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    const onRowDragEnd = (params: any) => {
      const { overIndex, node } = params
      const draggedRowData = node.data
      const currentIndex = pageData.dataList.indexOf(draggedRowData)
      pageData.dataList.splice(currentIndex, 1)
      pageData.dataList.splice(overIndex, 0, draggedRowData)
      pageData.dataList.forEach((o: any, index: number) => {
        o.serialNumber = index + 1
      })
      pageData.dataList = [...pageData.dataList]
      let names = pageData.dataList.map((o: any) => o.processName)
      pageData.dataList.forEach((o: any) => {
        o.flows = names.join('->')
      })
      //实时更新顺序
      post({
        url: 'pdm/ProductProcessSon/updateOrder',
        data: pageData.dataList,
      }).then((res: any) => {
        if (res.code === 200) {
        } else {
          Message.error(res.message)
        }
      })
    }

    const sectionSearch = (val: any) => {
      post({
        url: '/pdm/worksection/select',
        data: { sectionName: val },
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.sectionList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    const sectionChange = () => {
      dataForm.sectionName = ''
      dataForm.processId = null
      dataForm.processName = ''
      if (dataForm.sectionId) {
        dataForm.sectionName = pageData.sectionList.find(
          (o: any) => o.id == dataForm.sectionId
        ).sectionName
      }
    }

    const processSearch = (val: any) => {
      if (!dataForm.sectionName) {
        Message.warning('请先选择工段！')
        return
      }
      post({
        url: '/pdm/worksectionWorkprocedure/select',
        data: {
          sectionName: dataForm.sectionName,
          processName: val,
        },
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.nameList = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    return {
      sectionChange,
      processSearch,
      sectionSearch,
      onRowDragEnd,
      focusSelw1,
      handleSearchw1,
      pagingList1,
      huiche,
      localeText1,
      // listopen,
      focusSel2,
      handleSearchs1,
      closeNo,
      checkeded,
      gridReady1,
      defaultColDef1,
      tableColumns1,
      sideNo1,
      PageSize,
      change1,
      change2,
      total,
      tc,
      defaultColDef,
      gridReady,
      scroll,
      scrollbar,
      tablediv,
      downloadHandler,
      importHandler,
      hasChiese,
      deleteHandler,
      sideOk,
      sideOk1,
      formRef,
      formRef1,
      dataForm,
      addHandler,
      addHandler1,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      table1,
      rowKey,
      pageData,
      queryData,
      editHandler,
      editHandler2,
      selectHandler,
      options,
      loading,
      options12,
      loading2,
      handleSearch,
      exports,
      focusSel,
      headerShow,
      pageData2,
      deleteHandler1,
      doRefresh1,
    }
  },
  components: { Toolbar, PageTabelLayout },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(
    .ag-cell.ag-cell-first-right-pinned:not(.ag-cell-range-left):not(.ag-cell-range-single-cell)
  ) {
  text-align: center;
}
</style>
